#include "logging.h"

procedure TLogger::EnsureBufferSize(Integer ASize)
{
	if (sizeof(*FBuffer)/sizeof(FBuffer[0]) < ASize)
	{
		FBuffer = new char[ASize];
	};
};

procedure TLogger::IncreaseIndent()
{
	FIndentLevel++;
	EnsureBufferSize(FIndentLevel * sizeof(INDENT_CHAR));
	FBuffer[FIndentLevel] = INDENT_CHAR;
};

procedure TLogger::DecreaseIndent()
{
	if (FIndentLevel == 0)
	{
		DebugLn("Attempt to decrease indent level when already equal to 0.");
	}
	else
	{
		FIndentLevel--;
	}
};

procedure TLogger::DebugLn(PChar Message, Integer ALength)
{
	const char LINE_ENDING[] = {0x13,0x10};

	Integer RequiredSize;

	RequiredSize = sizeof(INDENT_CHAR) * FIndentLevel
		+ ALength
		+ strlen(LINE_ENDING);

	EnsureBufferSize(RequiredSize);

	sprintf(FBuffer,"%s%s",Message,LINE_ENDING);
	//memcpy(&Message[0], &FBuffer[FIndentLevel + 1], ALength);
	//memcpy(&LINE_ENDING[1], &FBuffer[FIndentLevel + 1 + ALength], sizeof(LINE_ENDING));

	WriteFile(FFileHandle, FBuffer, RequiredSize, NULL, NULL);
};

procedure TLogger::DebugLn(String Message)
{
	DebugLn(PChar(Message), strlen(Message));
};

procedure TLogger::DebugLn(String Message, Pointer Arguments)
{
	//DebugLn(Format(Message, Arguments));
};

procedure TLogger::DebugLnEnter(PChar Message, Integer ALength)
{
	DebugLn(Message, ALength);
	IncreaseIndent();
};

procedure TLogger::DebugLnEnter(String Message)
{
	DebugLnEnter(PChar(Message), strlen(Message));
};

procedure TLogger::DebugLnEnter(String Message, Pointer Arguments)
{
	//DebugLnEnter(Format(Message, Arguments));
};

procedure TLogger::DebugLnExit()
{
	DecreaseIndent();
};

TLogger::TLogger(String AFilePath)
{
	FIndentLevel = 0;
	FFileHandle = CreateFileA(AFilePath,
	GENERIC_READ | GENERIC_WRITE, //Read/Write
    0,                            // No Sharing
    NULL,                         // No Security
    OPEN_EXISTING,// Open existing port only
    0,               // Non Overlapped I/O              // FILE_FLAG_NO_BUFFERING,            // copied from the MFC version
    NULL);        // Null for Comm Devices);
	if (FFileHandle == NULL)
	{
		char vStr[100];
		sprintf(vStr,"Failed to create file ""%s""",AFilePath);
		MessageBoxA(NULL,vStr,"Error!",MB_OK | MB_ICONWARNING);
	};
};